import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  String _news = '';
  _getDate() async{
    var apiUrl = "http://192.168.1.7:3000/news";
    var result = await http.get(apiUrl);
    if(result.statusCode == 200){
      print(json.decode(result.body));

      setState(() {
        this._news = json.decode(result.body)['msg'];
      });
    }else{
      print(result.statusCode);
    }
  }

  _postDate() async{
    var apiUrl = "http://192.168.1.7:3000/dologin";
    var result = await http.post(apiUrl, body: {'username': '张三','age': '20'});
    if(result.statusCode == 200){
      print(json.decode(result.body));
    }else{
      print(result.statusCode);
    }
  }

  _dioGetData() async{
    var dio = Dio();
    Response response = await dio.get('http://192.168.1.7:3000/news');
    print(response.data);
  }

  _dioPostData() async{
    var dio = Dio();
    Response response = await dio.post('http://192.168.1.7:3000/dologin', data: {'username': '张三','age': '20'});
    print(response.data);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(this._news),
          RaisedButton(
            child: Text('Get请求数据'),
            onPressed: _getDate
          ),
          SizedBox(height: 10),
          RaisedButton(
            child: Text('Post提交数据'),
            onPressed: _postDate
          ),
          SizedBox(height: 10),
          RaisedButton(
            child: Text('跳转到http get请求Demo页面'),
            onPressed: (){
              Navigator.pushNamed(context, '/httpDemo');
            }
          ),
          Divider(),
          SizedBox(height: 10),
          RaisedButton(
            child: Text('Dio Get请求数据'),
            onPressed: _dioGetData
          ),
          SizedBox(height: 10),
          RaisedButton(
            child: Text('Dio Post提交数据'),
            onPressed: _dioPostData
          ),
          SizedBox(height: 10),
          RaisedButton(
            child: Text('跳转到Dio get请求Demo页面'),
            onPressed: () {
              Navigator.pushNamed(context, '/dioHttp');
            }
          )
        ], 
      )
    );
  }
}
